package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController_1 {

    @Value("${reggie.path}")
    public String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {   //  看一下前端页面文件的名字是什么

        //获取源文件的名称
        String originalFilename = file.getOriginalFilename();
        //获取源文件的后缀名称
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //通过UUID生成临时文件名称
        String fileName = UUID.randomUUID().toString() + suffix;
        //将临时文件转存到指定地点
        //进行指定路径是否存在的判定
        File file1 = new File(basePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //进行文件存在与否的判断
            File file = new File(basePath + name);
            if (!file.exists()) {
                return;
            }
            //获取输入流读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //通过response获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //通过IOUtils工具类的copy() 进行文件的传输.
            IOUtils.copy(fileInputStream, outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
